package org.dxy.trigger.http.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.api.dto.request.productionLine.CreateProductionLineRequestDto;
import org.dxy.api.dto.request.productionLine.UpdateProductionLineRequestDto;
import org.dxy.api.dto.response.OptionDto;
import org.dxy.api.dto.response.R;
import org.dxy.domain.command.productionLine.*;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.infrastructure.persistent.po.query.ProductionLineBasicViewPo;
import org.dxy.infrastructure.persistent.service.FactoryViewService;
import org.dxy.infrastructure.persistent.service.WorkshopViewService;
import org.dxy.infrastructure.persistent.service.ProductionLineBasicViewService;
import org.dxy.trigger.http.service.ProductionLineApplicationService;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 产线应用服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductionLineApplicationServiceImpl implements ProductionLineApplicationService {
    private final CommandHandler<CreateProductionLineCommand, Long> CreateProductionLineCommandHandler;
    private final CommandHandler<RemoveProductionLineCommand, Void> RemoveProductionLineHandler;
//    private final CommandHandler<DeleteProductionLineCommand, Void> deleteCommandHandler;
    private final ProductionLineBasicViewService productionLineBasicViewService;
    // 注入工厂和车间服务来获取冗余信息
    private final FactoryViewService factoryViewService;
    private final WorkshopViewService workshopViewService;

    @Override
    @Transactional
    public R<Void> createProductionLine(CreateProductionLineRequestDto dto) {
        log.info("创建产线，请求参数：{}", dto);
        
        // 检查工厂是否存在并获取工厂信息
        var factory = factoryViewService.getById(dto.getFactoryId());
        if (factory == null) {
            return R.fail("所属工厂不存在");
        }
        
        // 检查车间是否存在并获取车间信息
        var workshop = workshopViewService.getById(dto.getWorkshopId());
        if (workshop == null) {
            return R.fail("所属车间不存在");
        }
        
        // 检查产线编码是否已存在
        if (productionLineBasicViewService.existsByLineCode(dto.getLineCode())) {
            return R.fail("产线编码已存在");
        }
        
        CreateProductionLineCommand command = new CreateProductionLineCommand(dto.getLineCode());

        CommandResult<Long> result = CreateProductionLineCommandHandler.handle(command);
        if (!result.success()) {
            log.error("创建产线失败：{}", result.msg());
            return R.fail(result.msg());
        }
        
        Long lineId = result.data();
        
        // 构建位置信息：工厂名称-车间名称-产线名称
        String location = String.format("%s-%s-%s", factory.getFactoryName(), workshop.getWorkshopName(), dto.getLineName());
        
        ProductionLineBasicViewPo entity = ProductionLineBasicViewPo.builder()
                .id(lineId)
                .lineCode(dto.getLineCode())
                .lineName(dto.getLineName())
                .factoryId(dto.getFactoryId())
                .factoryName(factory.getFactoryName())  // 保存工厂名称冗余信息
                .workshopId(dto.getWorkshopId())
                .workshopName(workshop.getWorkshopName())  // 保存车间名称冗余信息
                .lineType(dto.getLineType())
                .status("enable")
                .location(location)  // 自动生成位置信息
                .maxDeviceCapacity(dto.getMaxDeviceCapacity())
                .description(dto.getDescription())
                .build();
        productionLineBasicViewService.save(entity);
        return R.ok("创建成功");
    }

    @Override
    public R<Page<ProductionLineBasicViewPo>> list(Page<ProductionLineBasicViewPo> page, ProductionLineBasicViewPo query) {
        LambdaQueryWrapper<ProductionLineBasicViewPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(query.getLineName()), ProductionLineBasicViewPo::getLineName, query.getLineName())
                .eq(StringUtils.isNotBlank(query.getStatus()), ProductionLineBasicViewPo::getStatus, query.getStatus());

        return R.ok(productionLineBasicViewService.page(page, wrapper));
    }

    @Override
    @Transactional
    public R<Void> update(Long id, UpdateProductionLineRequestDto dto) {
        log.info("更新产线，ID：{}，参数：{}", id, dto);
//        UpdateProductionLineCommand command = UpdateProductionLineCommand.builder()
//                .lineId(id)
//                .lineName(dto.getLineName())
//                .description(dto.getDescription())
//                .status(dto.getStatus())
//                .location(dto.getLocation())
//                .build();
//        CommandResult<Void> result = updateCommandHandler.handle(command);
//        if (!result.success()) {
//            log.error("更新失败：{}", result.msg());
//            return R.fail(result.msg());
//        }
//        ProductionLineBasicViewEntity entity = productionLineBasicViewService.getById(id);
//        if (entity != null) {
//            entity.setLineName(dto.getLineName());
//            entity.setDescription(dto.getDescription());
//            entity.setStatus(dto.getStatus());
//            entity.setLocation(dto.getLocation());
//            productionLineBasicViewService.updateById(entity);
//        }
        return R.ok("更新成功");
    }

    @Override
    @Transactional
    public R<Void> delete(Long id) {
        log.info("删除产线，ID：{}", id);
        RemoveProductionLineCommand command = RemoveProductionLineCommand.builder()
                .lineId(id)
                .build();
        CommandResult<Void> result = RemoveProductionLineHandler.handle(command);
        if (!result.success()) {
            log.error("删除失败：{}", result.msg());
            return R.fail(result.msg());
        }
        productionLineBasicViewService.removeById(id);
        return R.ok("删除成功");
    }

    @Override
    @Transactional
    public R<Void> batchDelete(List<Long> ids) {
        log.info("批量删除产线，IDs：{}", ids);
        for (Long id : ids) {
            RemoveProductionLineCommand command = RemoveProductionLineCommand.builder()
                    .lineId(id)
                    .build();
            CommandResult<Void> result = RemoveProductionLineHandler.handle(command);
            if (!result.success()) {
                log.error("删除失败：{}", result.msg());

                return R.fail(result.msg());
            }
            productionLineBasicViewService.removeById(id);
        }
        return R.ok("批量删除成功");
    }

    @Override
    public R<ProductionLineBasicViewPo> getById(Long id) {
        ProductionLineBasicViewPo ProductionLineBasicViewPo = productionLineBasicViewService.getById(id);
        return R.ok(ProductionLineBasicViewPo,"获取产品详情成功");
    }

    @Override
    public R<List<ProductionLineBasicViewPo>> getEnabledProductionLines() {
        try {
            log.info("开始查询启用状态的产线列表");
            
            LambdaQueryWrapper<ProductionLineBasicViewPo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductionLineBasicViewPo::getStatus, "enable");
            queryWrapper.orderByAsc(ProductionLineBasicViewPo::getLineName);
            
            List<ProductionLineBasicViewPo> productionLines = productionLineBasicViewService.list(queryWrapper);
            
            log.info("查询启用状态的产线列表成功: count={}", productionLines.size());
            return R.ok(productionLines, "查询成功");
            
        } catch (Exception e) {
            log.error("查询启用状态的产线列表失败", e);
            return R.fail("查询启用状态的产线列表失败: " + e.getMessage());
        }
    }

    @Override
    public R<List<OptionDto>> getProductionLineOptions() {
        try {
            log.info("开始查询产线选项列表");
            
            LambdaQueryWrapper<ProductionLineBasicViewPo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductionLineBasicViewPo::getStatus, "enable");
            queryWrapper.orderByAsc(ProductionLineBasicViewPo::getLineName);
            
            List<ProductionLineBasicViewPo> productionLines = productionLineBasicViewService.list(queryWrapper);
            
            List<OptionDto> options = productionLines.stream()
                    .map(line -> OptionDto.builder()
                            .id(String.valueOf(line.getId()))
                            .name(line.getLineName())
                            .code(line.getLineCode())
                            .description(line.getDescription())
                            .build())
                    .collect(java.util.stream.Collectors.toList());
            
            log.info("查询产线选项列表成功: count={}", options.size());
            return R.ok(options, "查询成功");
            
        } catch (Exception e) {
            log.error("查询产线选项列表失败", e);
            return R.fail("查询产线选项列表失败: " + e.getMessage());
        }
    }
}
